import CryptoJS from 'crypto-js'

const KEY = import.meta.env.VITE_ENCRYPT_KEY
const IV = import.meta.env.VITE_ENCRYPT_IV

export function encode(
    str: string | CryptoJS.lib.WordArray,
    key = '',
    iv = ''
) {
    if (!key) key = KEY
    if (!iv) iv = IV
    const encrypted = CryptoJS.AES.encrypt(str, CryptoJS.enc.Utf8.parse(key), {
        iv: CryptoJS.enc.Utf8.parse(iv),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    })
    return encrypted.toString()
}

export function decode(encryptedStr: string, key = '', iv = '') {
    if (!key) key = KEY
    if (!iv) iv = IV
    const bytes = CryptoJS.AES.decrypt(
        encryptedStr,
        CryptoJS.enc.Utf8.parse(key),
        {
            iv: CryptoJS.enc.Utf8.parse(iv),
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        }
    )
    return CryptoJS.enc.Utf8.stringify(bytes)
}
